package comp302.prototype.slide;

import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JPanel;

import comp302.prototype.PreviewPanel;
import comp302.prototype.xml.XMLNode;

public class SlideController {
	private PreviewPanel previewPanel;
	private JPanel slidePanel;
	private ArrayList<SlideItem> slideItems;
	private int index;

	public SlideController(PreviewPanel previewPanel, JPanel slidePanel) {
		this.previewPanel = previewPanel;
		this.slidePanel = slidePanel;
		slideItems = new ArrayList<SlideItem>();
		index = -1;
	}

	public SlideItem getCurrent() {
		return slideItems.get(index);
	}

	public int appendNew() {
		SlideItem slideItem = new SlideItem();
		int appendIndex = slideItems.size();
		PreviewItem previewItem = new PreviewItem(appendIndex);

		slideItems.add(slideItem);
		previewPanel.getPreviewSection().add(previewItem);
		previewPanel.revalidate();
		return appendIndex;
	}

	public void show(int index) {
		this.index = index;

		slidePanel.removeAll();
		slidePanel.add(slideItems.get(index));
		slidePanel.revalidate();
		slidePanel.repaint();
	}

	public int getSlideIndex(SlideItem slideItem) {
		return slideItems.indexOf(slideItem);
	}

	public XMLNode toXML() {
		XMLNode node = new XMLNode("prototype");
		Iterator<SlideItem> iterator = slideItems.iterator();

		while (iterator.hasNext()) {
			node.addChild(iterator.next().toXML());
		}

		return node;
	}

	public String toString() {
		return toXML().toString();
	}

	public void fromXML(XMLNode node) {
		slideItems = new ArrayList<SlideItem>();
		Iterator<XMLNode> iterator = node.childIterator();

		previewPanel.getPreviewSection().removeAll();

		for (int i = 0; iterator.hasNext(); i++) {
			SlideItem slideItem = new SlideItem();

			slideItem.fromXML(iterator.next());
			slideItems.add(slideItem);
			previewPanel.getPreviewSection().add(new PreviewItem(i));
			previewPanel.revalidate();
		}

		show(0);
	}
}
